<template>
  <div class="purchasenote_add">
    <el-main>
      <el-tabs value="first">
        <el-tab-pane label="基本信息" name="first">
          <!-- 顶部选项 -->
          <el-row :gutter="10">
            <el-col :span="2">
              <div style="margin-top: 7px;text-align: right;">
                <span style="color: red;">*</span>类型
              </div>
            </el-col>
            <el-col :span="3">
              <el-select v-model="sclxxz" disabled  placeholder="请选择">
                <el-option v-for="item in sclx" :key="item" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="3">
              <el-select v-model="cgryOrgysxz" disabled  filterable placeholder="请选择">
                <el-option v-for="(item,i) in cgryOrgys" :key="i" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="2">
              <div style="margin-top: 7px;text-align: right;">
                仓库
              </div>
            </el-col>
            <el-col :span="3">
              <el-select v-model="cklxxz" disabled  placeholder="请选择">
                <el-option v-for="(item,i) in cklx" :key="i" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="2">
              <div style="margin-top: 7px;text-align: right;">
                <span style="color: red;">*</span>计划交货日期
              </div>
            </el-col>
            <el-col :span="4">
              <el-date-picker type="date" disabled  v-model="jhdate" value-format="yyyy-MM-dd" format="yyyy 年 MM 月 dd 日"
                placeholder="选择日期">
              </el-date-picker>
            </el-col>
            <el-col :span="2">
              <div style="margin-top: 7px;text-align: right;">
                排序方式
              </div>
            </el-col>
            <el-col :span="3">
              <el-select v-model="pxfsxz" disabled>
                <el-option v-for="item in pxfs" :key="item" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-col>
          </el-row>

          <div style="margin: 5px 0;">
            单据来源:
          </div>
          <div v-show="isshow">

            <el-row>
              <el-col :span="3">
                <div
                  style="text-align: center; font-size: 13px; line-height: 30px; color: #1890ff;border-bottom: 2px solid #1890ff;">
                  采购单商品清单</div>
              </el-col>
            </el-row>
            <el-row :gutter="10" style="border-top: 1px solid #d8d8d8; padding-top: 10px;">
              <el-col :span="1">
                <div style="margin-top: 7px; text-align: right;">商品</div>
              </el-col>
              <el-col :span="5">
                <el-select v-model="shoppingres" disabled  filterable :filter-method="searchshopping" placeholder="请选择">
                  <el-option v-for="(item,i) in shoppingName" :key="i" :label="item.name"
                    placeholder="请选商品名/助记码/编码/别名/关键字" :value="item.name">
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="3">
                <div style="margin-top: 7px; text-align: right;">数量</div>
              </el-col>
              <el-col :span="5">
                <el-input v-model="numberfunc" disabled  placeholder="请输入数量"></el-input>
              </el-col>
              <el-col :span="3">
                <el-button type="primary" @click="addfunc">添加</el-button>
              </el-col>
            </el-row>
            <div style="text-align: right; margin-bottom: 20px;">
              <el-button @click="drawer = true">表头设置</el-button>
            </div>
            <el-drawer title="选择表头显示列" size="15%" :visible.sync="drawer">
              <div v-for="(res,i) in tablecheckAll" :key="i" style="padding: 10px; line-height: 30PX;">
                <el-checkbox :disabled="tableforbid.indexOf(res) !== -1" v-model="tablecheckeds" :label="res">{{res}}
                </el-checkbox>
              </div>
            </el-drawer>

            <el-table border :data="tableData" style="width: 100%;margin-bottom:10px">
              <el-table-column v-if="tablecheckeds.indexOf('序号')>-1" prop="date" label="序号" type="index" width="50">
              </el-table-column>
              <el-table-column v-if="tablecheckeds.indexOf('商品图片')>-1" prop="name" label="商品图片" width="120">
                <template slot-scope="scope">
                  <img :src="scope.row.goodsImages.path" alt="购物车">
                  <!-- {{scope.row}} -->
                </template>
              </el-table-column>
              <el-table-column prop="name" v-if="tablecheckeds.indexOf('商品')>-1" label="商品">
              </el-table-column>
              <el-table-column prop="unit" v-if="tablecheckeds.indexOf('单位')>-1" label="单位">
              </el-table-column>
              <el-table-column prop="wu" v-if="tablecheckeds.indexOf('近一次采购')>-1" label="近一次采购">
              </el-table-column>
              <el-table-column prop="wu" v-if="tablecheckeds.indexOf('采购询价')>-1" label="采购询价" width="120">
              </el-table-column>
              <el-table-column prop="wu" v-if="tablecheckeds.indexOf('市场参考价')>-1" label="市场参考价" width="100">
              </el-table-column>
              <el-table-column prop="procurementprice" v-if="tablecheckeds.indexOf('采购价')>-1" label="采购价" width="120">
                <template slot-scope="scope">
                 <!-- <el-input v-model.number="scope.row.procurementprice" type="number"
                    @input="test(scope.$index,tableData,3)" placeholder="请输入内容"></el-input> -->
                    {{scope.row.procurementprice}}
                  <!-- <el-input v-model="result" placeholder="请输入内容"></el-input> -->
                  <!-- <input style="width: 100%;" v-model="scope.row.procurementprice" type="number"> -->
                </template>
              </el-table-column>
              <el-table-column prop="topurchasequantity" v-if="tablecheckeds.indexOf('待采购量')>-1" label="待采购量"
                width="120">
                <template slot-scope="scope">
                  <!-- <el-input v-model.number="scope.row.topurchasequantity" type="number"
                    @input="test(scope.$index,tableData,1)" placeholder="请输入内容"></el-input>
                     -->
                     {{scope.row.topurchasequantity}}
                  <!-- <el-input v-model="scope.row.topurchasequantity"></el-input> -->
                </template>
              </el-table-column>
              <el-table-column prop="purchaseamount" v-if="tablecheckeds.indexOf('采购金额')>-1" label="采购金额" width="120">
                <template slot-scope="scope">
                 <!-- <el-input v-model.number="scope.row.purchaseamount" type="number"
                    @input="test(scope.$index,tableData,2)" placeholder="请输入内容"></el-input> -->
                    {{scope.row.purchaseamount}}
                </template>
              </el-table-column>
              <el-table-column prop="remark" v-if="tablecheckeds.indexOf('备注')>-1" label="备注" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remark" disabled placeholder="请输入内容"></el-input>
                </template>
              </el-table-column>
              <!-- <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-button @click.native.prevent="deleteRow(scope.$index, tableData)" type="text" size="small">
                    移除
                  </el-button>
                </template>
              </el-table-column> -->
            </el-table>
            <div style="width: 100%;margin-bottom: 10px;text-align: right;padding-right: 20px;">合计(含税) : <span
                style="color: red;">{{totleprice}}</span></div>
            <div style="margin-bottom: 40px;">
              备注：<el-input v-model="beizhus" disabled placeholder="请输入内容"></el-input>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-main>
    <div style="position: fixed;bottom: 0;background-color: #FFFFFF; width: 100%;line-height: 80px;z-index: 9;">
      <el-button @click="savefunc" v-if="$route.meta.title!='详情'" style="margin-left: 40px;" type="primary">保存</el-button>
      <el-button @click="returnpre" type="primary" plain>取消</el-button>
    </div>
  </div>
</template>

<script>
  import {
    getShopping,
    getwarehouse,
    addfuntoo,
    addfun,
    getList,
    getitemlist,
    setorderedit,
    setorderitemedit
  } from '@/api/purchase/purchasenote.js'
  import {
    getbuyerAll
  } from '@/api/purchase/buyerapi.js'
  import {
    getsupplierAll
  } from '@/api/purchase/supplierapi.js'
  import paramsData from '@/utils/data.js'
  export default {
    computed: {
      goodsPricecont() {
        let cont = 0
        this.tableData.forEach((x) => {
          cont = cont + parseFloat(x.purchaseamount)
        })
        return cont
      }
    },
    watch: {
      async sclxxz(val, newval) {
        if (val == "市场自采") {
          let res = await getbuyerAll({})
          this.cgryOrgys = res.list
        } else {
          let res = await getsupplierAll({})
          this.cgryOrgys = res.list
        }
      },
      cgryOrgysxz(val, newval) {
        if (this.cklxxz != "" && this.jhdate != "" && this.pxfsxz != "") {
          this.isshow = true
        }
      },
      cklxxz(val, newval) {
        if (this.cklxxz != "" && this.jhdate != "" && this.pxfsxz != "" && this.cgryOrgysxz !== "") {
          this.isshow = true
        }
      },
      jhdate(val, newval) {
        if (this.cklxxz != "" && this.jhdate != "" && this.pxfsxz != "" && this.cgryOrgysxz !== "") {
          this.isshow = true
        }
      },
      pxfsxz(val, newval) {
        if (this.cklxxz != "" && this.jhdate != "" && this.pxfsxz != "" && this.cgryOrgysxz !== "") {
          this.isshow = true
        }
      }
    },
    data() {
      return {
        tablecheckAll: ["序号", "商品图片", "商品", "单位", "近一次采购", "采购询价", "市场参考价", "采购价", "待采购量", "采购金额", "备注"],
        tablecheckeds: ["序号", "商品图片", "商品", "单位", "近一次采购", "采购询价", "市场参考价", "采购价", "待采购量", "采购金额", "备注"],
        tableforbid: ["序号", "商品图片", "商品", "采购价", "待采购量", "采购金额"],
        drawer: false,
        shoppingName: "", //商品名字
        shoppingres: "", //商品结果
        sclx: ["市场自采", "供应商直供"], //市场类型
        sclxxz: "", //最终选择结果
        cklx: "", //仓库类型
        cklxxz: "", //仓库最终选择类型
        person: "", //人员选择
        cgryOrgys: "", //采购人员或供应商
        cgryOrgysxz: "", //采购人员或供应商选择
        jhdate: "", //交货日期
        pxfs: ["手动新增排序", "按一二级分类排序"], //排序
        pxfsxz: "", //排序方式选择
        numberfunc: 1, //数量
        isshow: false,
        tableData: [],
        totleprice: "0", //总金额
        beizhus: "", //备注
      }
    },
    async created() {
      //获取仓库列表
      let ckres = await getwarehouse({})
      this.cklx = ckres.data.list
      if (this.$route.params.id) {
        this.isshow = true
        let data = {
          id: this.$route.params.id
        }
        let resedit = await getList(1, 1, data)
        let gitres = resedit.list[0]
        this.beizhus = gitres.remarks
        this.jhdate = gitres.delivery_date
        this.sclxxz = gitres.type
        this.cklx.forEach((item)=>{
          if(item.id == gitres.warehouse_id){
            this.cklxxz = item.name
          }
        })
        // this.cklxxz = gitres.warehouse_id
        if (this.sclxxz == "市场自采") {
          let res = await getbuyerAll({})
          this.cgryOrgys = res.list
        } else {
          let res = await getsupplierAll({})
          this.cgryOrgys = res.list
        }
        if(gitres.purchaser_name){
        this.cgryOrgysxz = gitres.purchaser_name
        }else{
          this.cgryOrgysxz = gitres.supplier_name
        }
        let shoppingres = await getitemlist(20, 1, gitres.id)
        let cont = 0
        shoppingres.list.forEach(async (item) => {
          let data = {
            name: item.product_name
          }
          let res = await getShopping(data)
          res = res.data.list
          let newarr = res.map((items) => {
          cont = cont+parseFloat(item.subtotal/100.0)
            return {
              ...items,
              procurementprice: item.price/100,
              editid:item.id,
              topurchasequantity: item.qty,
              purchaseamount: parseFloat(item.subtotal/100.0),
              remark:item.remarks,
            }
          })
          newarr.forEach((e) => {
            this.tableData.push(e)
          })
        this.totleprice = cont
        })
      }
    },
    methods: {
      async searchshopping(val) {
        let data = {
          name: val
        }
        let res = await getShopping(data)
        this.shoppingName = res.data.list
      },
      async savefunc() {
        // 获取采购员或供应商
        let purchaserId = ""
        let supplierId = ""
        let warehouseId = "" //仓库id
        if (this.sclxxz == "市场自采") {
          this.cgryOrgys.forEach((item) => {
            if (this.cgryOrgysxz == item.name) {
              purchaserId = item.id
            }
          })
        } else {
          this.cgryOrgys.forEach((item) => {
            if (this.cgryOrgysxz == item.name) {
              supplierId = item.id
            }
          })
        }

        this.cklx.forEach((item) => {
          if (item.name == this.cklxxz) {
            warehouseId = item.id
          }
        })

        if(this.$route.params.id){
          let timestamp = Date.parse(new Date()) / 1000
          let data ={
            id: this.$route.params.id,
            wsId: "1",
            warehouseId:warehouseId,
            type: this.sclxxz,
            purchaserId:purchaserId,
            supplierId: supplierId,
            total: this.totleprice*100,
            status:"1",
            deliveryDate: this.jhdate,
            remarks: this.beizhus,
            utime:timestamp,
            uuser:"tom"
          }
         let res = await setorderedit(data)

         this.tableData.forEach(async (item, i) => {
           let timestamp = Date.parse(new Date()) / 1000
           let dataobject = {
             id: item.editid,
             qty: item.topurchasequantity,
             unit: item.unit,
             price: item.procurementprice*100,
             subtotal: parseInt(item.purchaseamount * 100),
             remarks: item.remark,
             timeDelivery: timestamp,
             status:"1"
           }
           let r = await setorderitemedit(dataobject)
         })
         this.$message({
           message: "修改成功",
           type: "success"
         })
        }else{
          let data = {
            wsId: "1", //站点
            type: this.sclxxz, //市场类型
            deliveryDate: this.jhdate, //计划收货日期
            remarks: this.beizhus, //备注
            warehouseId: warehouseId, //仓库id
            purchaserId: purchaserId, //采购员id
            supplierId: supplierId, //供应商id
            total: this.totleprice*100, //金额 分为单位
            status: "1", //订单状态
          }
          let res = await addfun(data)
          let orderid = res.data.orderid
          this.tableData.forEach(async (item, i) => {
            let timestamp = Date.parse(new Date()) / 1000

            let dataobject = {
              orderId: orderid,
              productName: item.name,
              productId: item.id,
              qty: item.topurchasequantity,
              unit: item.unit,
              price: item.procurementprice * 100,
              subtotal: item.purchaseamount * 100,
              remarks: item.remark,
              ctime: timestamp
            }
            let r = await addfuntoo(dataobject)
          })
          this.$message({
            message: "保存成功",
            type: "success"
          })
          // 保存成功准备跳转
        }


          this.$router.push("/purchase/purchasenote")


      },
      returnpre() {
        this.$router.push("/purchase/purchasenote")
      },
      deleteRow(index, rows) {
        rows.splice(index, 1);
      },
      test(index, data, type) {
        let res
        switch (type) {
          case 3:
            res = data[index].procurementprice
            if (res == "") {
              data[index].procurementprice = 0
            }
            data[index].purchaseamount = (parseFloat(data[index].topurchasequantity) * parseFloat(data[index]
              .procurementprice)).toFixed(2)
            break
          case 1:
            res = data[index].topurchasequantity
            if (res == "") {
              data[index].topurchasequantity = 0
            }
            data[index].purchaseamount = (parseFloat(data[index].topurchasequantity) * parseFloat(data[index]
              .procurementprice)).toFixed(2)
            break
          case 2:
            res = data[index].purchaseamount
            if (res == "") {
              data[index].purchaseamount = 0
            }
            if (data[index].topurchasequantity === 0) {
              data[index].topurchasequantity = 1
            }
            data[index].procurementprice = (parseFloat(data[index].purchaseamount) / parseFloat(data[index]
              .topurchasequantity)).toFixed(2)
            break
        }
        let cont = 0
        this.tableData.forEach((x) => {
          cont = cont + parseFloat(x.purchaseamount)
        })
        this.totleprice = cont
      },
      addfunc() {
        if (this.shoppingres == "") {
          return
        }
        let res = this.shoppingName.filter((res) => {
          return res.name == this.shoppingres
        })
        let tablelength = this.tableData.length
        for (let i = 0; i < tablelength; i++) {
          if (this.tableData[i].name == res[0].name) {
            this.$message({
              message: "该商品已添加",
              type: "error"
            })
            return
          }
        }

        let newarr = res.map((item) => {
          return {
            ...item,
            procurementprice: 0.00,
            topurchasequantity: this.numberfunc,
            purchaseamount: 0.00
          }
        })
        newarr.forEach((e) => {
          this.tableData.push(e)
        })
      }

    }
  }
</script>

<style>
  .purchasenote_add .el-date-editor.el-input {
    width: 100% !important;
  }

  .purchasenote_add .cell img {
    width: 50px;
    /* height: 100%; */
  }

  .purchasenote_add .cell input {
    padding-right: 0;
  }

  .purchasenote_add #el-drawer__title {
    border-bottom: 1px solid #f3f3f3
  }

  /*  .purchasenote_add .el-main{
    height: 100% !important;
    overflow: auto !important;
  } */
</style>
